<?php
namespace plugin\ky_shouyin\app\controller;

use support\Request;
use support\Response;
use support\Db;
use support\View;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\Fill;

class GoodsController extends BaseController
{
    /**
     * 商品列表页面
     */
    public function index()
    {
        return $this->view('goods/index');
    }

    /**
     * 获取商品列表数据
     */
    public function list(Request $request)
    {
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 15);
        $keyword = $request->input('keyword', '');
        $categoryId = $request->input('category_id', '');
        
        $query = Db::table('ky_goods')
            ->leftJoin('ky_goods_category', 'ky_goods.category_id', '=', 'ky_goods_category.id')
            ->select('ky_goods.*', 'ky_goods_category.name as category_name');

        if ($keyword) {
            $query->where('ky_goods.name', 'like', "%{$keyword}%")
                  ->orWhere('ky_goods.code', 'like', "%{$keyword}%");
        }

        if ($categoryId) {
            $query->where('ky_goods.category_id', $categoryId);
        }

        $total = $query->count();
        $goods = $query->offset(($page - 1) * $limit)
                      ->limit($limit)
                      ->orderBy('ky_goods.id', 'desc')
                      ->get();

        return json(['code' => 0, 'msg' => 'success', 'count' => $total, 'data' => $goods]);
    }

    /**
     * 商品分类列表
     */
    public function categoryList()
    {
        $categories = Db::table('ky_goods_category')
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'asc')
            ->get();
            
        return json(['code' => 0, 'msg' => 'success', 'data' => $categories]);
    }

    /**
     * 商品分类管理
     */
    public function category()
    {
        return $this->view('goods/category');
    }

    /**
     * 添加商品分类
     */
    public function category_add(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 检查分类名称是否重复
                $exists = Db::table('ky_goods_category')
                    ->where('name', $data['name'])
                    ->where('parent_id', $data['parent_id'])
                    ->exists();
                    
                if ($exists) {
                    return json(['code' => 1, 'msg' => '同级分类下已存在相同名称']);
                }

                // 获取父级分类信息
                $level = 1;
                $path = '';
                if ($data['parent_id'] > 0) {
                    $parent = Db::table('ky_goods_category')
                        ->where('id', $data['parent_id'])
                        ->first();
                    if ($parent) {
                        $level = $parent->level + 1;
                        $path = $parent->path ? $parent->path . ',' . $parent->id : $parent->id;
                    }
                }
                
                // 添加分类
                $id = Db::table('ky_goods_category')->insertGetId([
                    'parent_id' => $data['parent_id'],
                    'name' => $data['name'],
                    'level' => $level,
                    'path' => $path,
                    'sort' => $data['sort'] ?? 0,
                    'status' => $data['status'] ?? 1,
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                
                return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $id]]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
        
        return $this->view('goods/category_add');
    }

    /**
     * 编辑商品分类
     */
    public function category_edit(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 检查分类名称是否重复
                $exists = Db::table('ky_goods_category')
                    ->where('name', $data['name'])
                    ->where('parent_id', $data['parent_id'])
                    ->where('id', '!=', $data['id'])
                    ->exists();
                    
                if ($exists) {
                    return json(['code' => 1, 'msg' => '同级分类下已存在相同名称']);
                }

                // 获取父级分类信息
                $level = 1;
                $path = '';
                if ($data['parent_id'] > 0) {
                    $parent = Db::table('ky_goods_category')
                        ->where('id', $data['parent_id'])
                        ->first();
                    if ($parent) {
                        $level = $parent->level + 1;
                        $path = $parent->path ? $parent->path . ',' . $parent->id : $parent->id;
                    }
                }
                
                // 更新分类
                Db::table('ky_goods_category')
                    ->where('id', $data['id'])
                    ->update([
                        'parent_id' => $data['parent_id'],
                        'name' => $data['name'],
                        'level' => $level,
                        'path' => $path,
                        'sort' => $data['sort'] ?? 0,
                        'status' => $data['status'] ?? 1,
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                
                return json(['code' => 0, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '更新失败：' . $e->getMessage()]);
            }
        }
        
        $id = $request->get('id');
        $category = Db::table('ky_goods_category')
            ->where('id', $id)
            ->first();
            
        if (!$category) {
            return json(['code' => 1, 'msg' => '分类不存在']);
        }

        // 将对象转换为数组并确保所有必要的字段都存在
        $categoryData = [
            'id' => $category->id,
            'parent_id' => $category->parent_id,
            'name' => $category->name,
            'sort' => $category->sort,
            'status' => $category->status,
            'level' => $category->level,
            'path' => $category->path
        ];
        
        return $this->view('goods/category_edit', [
            'category' => $categoryData
        ]);
    }

    /**
     * 删除商品分类
     */
    public function category_delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            // 检查是否有子分类
            $hasChildren = Db::table('ky_goods_category')
                ->where('parent_id', $id)
                ->exists();
                
            if ($hasChildren) {
                return json(['code' => 1, 'msg' => '该分类下有子分类，请先删除子分类']);
            }
            
            // 检查分类下是否有商品
            $hasGoods = Db::table('ky_goods')
                ->where('category_id', $id)
                ->exists();
                
            if ($hasGoods) {
                return json(['code' => 1, 'msg' => '该分类下有商品，无法删除']);
            }
            
            // 删除分类
            Db::table('ky_goods_category')->where('id', $id)->delete();
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 添加商品
     */
    public function add(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 检查商品编码是否重复
                if (!empty($data['code'])) {
                    $exists = Db::table('ky_goods')
                        ->where('code', $data['code'])
                        ->exists();
                        
                    if ($exists) {
                        return json(['code' => 1, 'msg' => '商品编码已存在']);
                    }
                }
                
                // 添加商品
                $id = Db::table('ky_goods')->insertGetId([
                    'category_id' => $data['category_id'],
                    'code' => $data['code'] ?? '',
                    'name' => $data['name'],
                    'price' => $data['price'],
                    'original_price' => $data['original_price'] ?? 0,
                    'unit' => $data['unit'] ?? '',
                    'stock' => $data['stock'] ?? 0,
                    'min_stock' => $data['min_stock'] ?? 0,
                    'status' => $data['status'] ?? 1,
                    'image' => $data['image'] ?? '',
                    'remark' => $data['remark'] ?? '',
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
                
                return json(['code' => 0, 'msg' => '添加成功', 'data' => ['id' => $id]]);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '添加失败：' . $e->getMessage()]);
            }
        }
        
        return $this->view('goods/add');
    }

    /**
     * 编辑商品
     */
    public function edit(Request $request)
    {
        if ($request->method() === 'POST') {
            $data = $request->post();
            
            try {
                // 检查商品编码是否重复
                if (!empty($data['code'])) {
                    $exists = Db::table('ky_goods')
                        ->where('code', $data['code'])
                        ->where('id', '!=', $data['id'])
                        ->exists();
                        
                    if ($exists) {
                        return json(['code' => 1, 'msg' => '商品编码已存在']);
                    }
                }
                
                // 更新商品
                Db::table('ky_goods')
                    ->where('id', $data['id'])
                    ->update([
                        'category_id' => $data['category_id'],
                        'code' => $data['code'] ?? '',
                        'name' => $data['name'],
                        'price' => $data['price'],
                        'original_price' => $data['original_price'] ?? 0,
                        'unit' => $data['unit'] ?? '',
                        'stock' => $data['stock'] ?? 0,
                        'min_stock' => $data['min_stock'] ?? 0,
                        'status' => $data['status'] ?? 1,
                        'image' => $data['image'] ?? '',
                        'remark' => $data['remark'] ?? '',
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                
                return json(['code' => 0, 'msg' => '更新成功']);
            } catch (\Exception $e) {
                return json(['code' => 1, 'msg' => '更新失败：' . $e->getMessage()]);
            }
        }
        
        $id = $request->get('id');
        $goods = Db::table('ky_goods')->where('id', $id)->first();
        
        return $this->view('goods/edit', ['goods' => $goods]);
    }

    /**
     * 删除商品
     */
    public function delete(Request $request)
    {
        $id = $request->post('id');
        
        try {
            // 检查商品是否可以删除（这里可以添加自己的业务逻辑）
            
            // 删除商品
            Db::table('ky_goods')->where('id', $id)->delete();
            
            return json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '删除失败：' . $e->getMessage()]);
        }
    }

    /**
     * 获取商品统计数据
     */
    public function stats()
    {
        try {
            // 获取商品总数和类型统计
            $goods = Db::table('ky_goods')
                ->selectRaw('COUNT(*) as total, 
                    SUM(CASE WHEN type = 1 THEN 1 ELSE 0 END) as normal,
                    SUM(CASE WHEN type = 2 THEN 1 ELSE 0 END) as service')
                ->first();
            
            // 获取库存预警数量
            $stock_warnings = Db::table('ky_goods')
                ->where('type', 1) // 只统计普通商品
                ->selectRaw('
                    SUM(CASE WHEN stock <= min_stock THEN 1 ELSE 0 END) as warning,
                    SUM(CASE WHEN stock < 5 THEN 1 ELSE 0 END) as stock_lt_5,
                    SUM(CASE WHEN stock < 10 THEN 1 ELSE 0 END) as stock_lt_10,
                    SUM(CASE WHEN stock < 15 THEN 1 ELSE 0 END) as stock_lt_15
                ')
                ->first();
            
            // 获取销售排行Top3
            $top_sales = Db::table('ky_goods')
                ->where('sales_count', '>', 0)
                ->orderBy('sales_count', 'desc')
                ->limit(3)
                ->get(['name', 'sales_count'])
                ->toArray();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'total' => $goods->total ?? 0,
                    'normal' => $goods->normal ?? 0,
                    'service' => $goods->service ?? 0,
                    'warning' => $stock_warnings->warning ?? 0,
                    'stock_lt_5' => $stock_warnings->stock_lt_5 ?? 0,
                    'stock_lt_10' => $stock_warnings->stock_lt_10 ?? 0,
                    'stock_lt_15' => $stock_warnings->stock_lt_15 ?? 0,
                    'top_sales' => $top_sales
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '获取统计数据失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 修改商品状态
     */
    public function status(Request $request)
    {
        try {
            $id = $request->post('id');
            $status = $request->post('status');
            
            if (!$id) {
                throw new \Exception('参数错误');
            }
            
            Db::table('ky_goods')->where('id', $id)->update([
                'status' => $status,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
            
            return json([
                'code' => 0,
                'msg' => '修改状态成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '修改状态失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 批量删除商品
     */
    public function batchDelete(Request $request)
    {
        try {
            $ids = $request->post('ids');
            
            if (!$ids || !is_array($ids)) {
                throw new \Exception('参数错误');
            }
            
            Db::table('ky_goods')->whereIn('id', $ids)->delete();
            
            return json([
                'code' => 0,
                'msg' => '删除成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '删除失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 导出商品
     */
    public function export(Request $request)
    {
        try {
            // 创建导出目录
            $exportDir = public_path() . '/export';
            if (!is_dir($exportDir)) {
                mkdir($exportDir, 0755, true);
            }

            // 获取选中的商品ID
            $ids = $request->get('ids');
            
            // 构建查询
            $query = Db::table('ky_goods')
                ->leftJoin('ky_goods_category', 'ky_goods.category_id', '=', 'ky_goods_category.id')
                ->select(
                    'ky_goods.code',
                    'ky_goods.name',
                    'ky_goods_category.name as category_name',
                    'ky_goods.type',
                    'ky_goods.price',
                    'ky_goods.member_price',
                    'ky_goods.original_price',
                    'ky_goods.unit',
                    'ky_goods.spec',
                    'ky_goods.stock',
                    'ky_goods.min_stock',
                    'ky_goods.status',
                    'ky_goods.remark'
                );
                
            // 如果有选中的商品ID，则只导出选中的商品
            if (!empty($ids)) {
                $idArray = explode(',', $ids);
                $query->whereIn('ky_goods.id', $idArray);
            }
            
            $goods = $query->orderBy('ky_goods.id', 'desc')->get();

            // 创建新的 Excel 对象
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(15);
            $sheet->getColumnDimension('B')->setWidth(30);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(12);
            $sheet->getColumnDimension('E')->setWidth(12);
            $sheet->getColumnDimension('F')->setWidth(12);
            $sheet->getColumnDimension('G')->setWidth(12);
            $sheet->getColumnDimension('H')->setWidth(10);
            $sheet->getColumnDimension('I')->setWidth(15);
            $sheet->getColumnDimension('J')->setWidth(10);
            $sheet->getColumnDimension('K')->setWidth(10);
            $sheet->getColumnDimension('L')->setWidth(10);
            $sheet->getColumnDimension('M')->setWidth(30);
            
            // 设置表头
            $headers = [
                'A1' => '商品编号',
                'B1' => '商品名称',
                'C1' => '商品分类',
                'D1' => '商品类型',
                'E1' => '零售价',
                'F1' => '会员价',
                'G1' => '进价',
                'H1' => '单位',
                'I1' => '规格',
                'J1' => '库存',
                'K1' => '最低库存',
                'L1' => '状态',
                'M1' => '备注'
            ];
            
            // 设置表头样式
            $style = [
                'font' => [
                    'bold' => true,
                    'color' => ['rgb' => '000000'],
                    'size' => 11,
                    'name' => '微软雅黑'
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical' => Alignment::VERTICAL_CENTER
                ],
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'E6E6E6']
                ]
            ];
            
            // 应用表头和样式
            foreach ($headers as $cell => $value) {
                $sheet->setCellValue($cell, $value);
                $sheet->getStyle($cell)->applyFromArray($style);
            }
            
            // 写入数据
            $row = 2;
            foreach ($goods as $item) {
                $sheet->setCellValue('A' . $row, $item->code);
                $sheet->setCellValue('B' . $row, $item->name);
                $sheet->setCellValue('C' . $row, $item->category_name);
                $sheet->setCellValue('D' . $row, $item->type == 1 ? '普通商品' : '服务商品');
                $sheet->setCellValue('E' . $row, $item->price);
                $sheet->setCellValue('F' . $row, $item->member_price);
                $sheet->setCellValue('G' . $row, $item->original_price);
                $sheet->setCellValue('H' . $row, $item->unit);
                $sheet->setCellValue('I' . $row, $item->spec);
                $sheet->setCellValue('J' . $row, $item->stock);
                $sheet->setCellValue('K' . $row, $item->min_stock);
                $sheet->setCellValue('L' . $row, $item->status == 1 ? '上架' : '下架');
                $sheet->setCellValue('M' . $row, $item->remark);
                $row++;
            }

            // 生成文件名
            $filename = '商品列表_' . date('YmdHis') . '.xlsx';
            $filepath = $exportDir . '/' . $filename;
            
            // 保存文件
            $writer = new Xlsx($spreadsheet);
            $writer->save($filepath);
            
            // 返回文件下载地址
            return json([
                'code' => 0,
                'msg' => '导出成功',
                'data' => [
                    'url' => '/export/' . $filename
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '导出失败：' . $e->getMessage()
            ]);
        }
    }

    /**
     * 导入商品
     */
    public function import(Request $request)
    {
        // GET请求显示导入页面
        if ($request->method() === 'GET') {
            return $this->view('goods/import');
        }
        
        // POST请求处理文件上传
        try {
            $file = $request->file('file');
            
            if (!$file || !$file->isValid()) {
                throw new \Exception('请选择要导入的文件');
            }
            
            $ext = strtolower($file->getUploadExtension());
            if (!in_array($ext, ['xlsx', 'xls'])) {
                throw new \Exception('只支持 Excel 文件导入');
            }

            // 创建上传目录
            $uploadDir = public_path() . '/upload';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }

            // 移动上传文件到指定目录
            $filename = uniqid() . '.' . $ext;
            $filepath = $uploadDir . '/' . $filename;
            move_uploaded_file($file->getRealPath(), $filepath);
            
            // 读取Excel文件
            $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReaderForFile($filepath);
            $reader->setReadDataOnly(true);
            $spreadsheet = $reader->load($filepath);
            $worksheet = $spreadsheet->getActiveSheet();
            $data = $worksheet->toArray();
            
            // 删除临时文件
            @unlink($filepath);
            
            // 移除表头
            array_shift($data);
            
            if (empty($data)) {
                throw new \Exception('文件内容为空');
            }
            
            $errors = [];
            $success = 0;
            
            // 开启事务
            Db::beginTransaction();
            
            try {
                foreach ($data as $index => $row) {
                    $rowNum = $index + 2; // Excel行号(去掉表头后从2开始)
                    
                    // 检查必填字段
                    if (empty($row[0]) || empty($row[1]) || empty($row[2]) || empty($row[3]) || empty($row[4])) {
                        $errors[] = "第{$rowNum}行：商品编号、商品名称、商品分类、商品类型、零售价为必填项";
                        continue;
                    }
                    
                    // 检查商品编号是否重复
                    $exists = Db::table('ky_goods')->where('code', $row[0])->exists();
                    if ($exists) {
                        $errors[] = "第{$rowNum}行：商品编号 {$row[0]} 已存在";
                        continue;
                    }
                    
                    // 检查商品类型是否有效
                    if (!in_array($row[3], ['普通商品', '服务商品'])) {
                        $errors[] = "第{$rowNum}行：商品类型必须是 普通商品 或 服务商品";
                        continue;
                    }
                    
                    // 检查状态是否有效
                    if (!empty($row[11]) && !in_array($row[11], ['上架', '下架'])) {
                        $errors[] = "第{$rowNum}行：状态必须是 上架 或 下架";
                        continue;
                    }
                    
                    // 检查价格字段是否为数字
                    if (!is_numeric($row[4])) {
                        $errors[] = "第{$rowNum}行：零售价必须是数字";
                        continue;
                    }
                    
                    if (!empty($row[5]) && !is_numeric($row[5])) {
                        $errors[] = "第{$rowNum}行：会员价必须是数字";
                        continue;
                    }
                    
                    if (!empty($row[6]) && !is_numeric($row[6])) {
                        $errors[] = "第{$rowNum}行：进价必须是数字";
                        continue;
                    }
                    
                    // 获取或创建分类
                    $category = Db::table('ky_goods_category')
                        ->where('name', $row[2])
                        ->first();
                        
                    if (!$category) {
                        $categoryId = Db::table('ky_goods_category')->insertGetId([
                            'name' => $row[2],
                            'status' => 1,
                            'created_at' => date('Y-m-d H:i:s'),
                            'updated_at' => date('Y-m-d H:i:s')
                        ]);
                    } else {
                        $categoryId = $category->id;
                    }
                    
                    // 插入商品数据
                    Db::table('ky_goods')->insert([
                        'code' => $row[0],
                        'name' => $row[1],
                        'category_id' => $categoryId,
                        'type' => $row[3] == '普通商品' ? 1 : 2,
                        'price' => $row[4],
                        'member_price' => $row[5] ?? 0,
                        'original_price' => $row[6] ?? 0,
                        'unit' => $row[7] ?? '',
                        'spec' => $row[8] ?? '',
                        'stock' => $row[9] ?? 0,
                        'min_stock' => $row[10] ?? 0,
                        'status' => isset($row[11]) ? ($row[11] == '上架' ? 1 : 0) : 1,
                        'remark' => $row[12] ?? '',
                        'created_at' => date('Y-m-d H:i:s'),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                    
                    $success++;
                }
                
                // 如果有错误，回滚事务
                if (!empty($errors)) {
                    Db::rollBack();
                    return json([
                        'code' => 1,
                        'msg' => '导入失败',
                        'data' => [
                            'errors' => $errors,
                            'success' => 0
                        ]
                    ]);
                }
                
                // 提交事务
                Db::commit();
                
                return json([
                    'code' => 0,
                    'msg' => "导入成功，共导入 {$success} 条数据",
                    'data' => [
                        'errors' => [],
                        'success' => $success
                    ]
                ]);
                
            } catch (\Exception $e) {
                Db::rollBack();
                throw $e;
            }
            
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '导入失败：' . $e->getMessage(),
                'data' => [
                    'errors' => [$e->getMessage()],
                    'success' => 0
                ]
            ]);
        }
    }

    /**
     * 下载导入模板
     */
    public function importTemplate()
    {
        try {
            // 创建导出目录
            $exportDir = public_path() . '/export';
            if (!is_dir($exportDir)) {
                mkdir($exportDir, 0755, true);
            }

            // 创建新的 Excel 对象
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            
            // 设置列宽
            $sheet->getColumnDimension('A')->setWidth(15);
            $sheet->getColumnDimension('B')->setWidth(30);
            $sheet->getColumnDimension('C')->setWidth(15);
            $sheet->getColumnDimension('D')->setWidth(12);
            $sheet->getColumnDimension('E')->setWidth(12);
            $sheet->getColumnDimension('F')->setWidth(12);
            $sheet->getColumnDimension('G')->setWidth(12);
            $sheet->getColumnDimension('H')->setWidth(10);
            $sheet->getColumnDimension('I')->setWidth(15);
            $sheet->getColumnDimension('J')->setWidth(10);
            $sheet->getColumnDimension('K')->setWidth(10);
            $sheet->getColumnDimension('L')->setWidth(10);
            $sheet->getColumnDimension('M')->setWidth(30);
            
            // 设置表头
            $headers = [
                'A1' => '商品编号(*)',
                'B1' => '商品名称(*)',
                'C1' => '商品分类(*)',
                'D1' => '商品类型(*)',
                'E1' => '零售价(*)',
                'F1' => '会员价',
                'G1' => '进价',
                'H1' => '单位',
                'I1' => '规格',
                'J1' => '库存',
                'K1' => '最低库存',
                'L1' => '状态',
                'M1' => '备注'
            ];
            
            // 设置表头样式
            $style = [
                'font' => [
                    'bold' => true,
                    'color' => ['rgb' => '000000'],
                    'size' => 11,
                    'name' => '微软雅黑'
                ],
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical' => Alignment::VERTICAL_CENTER
                ],
                'fill' => [
                    'fillType' => Fill::FILL_SOLID,
                    'startColor' => ['rgb' => 'E6E6E6']
                ]
            ];
            
            // 应用表头和样式
            foreach ($headers as $cell => $value) {
                $sheet->setCellValue($cell, $value);
                $sheet->getStyle($cell)->applyFromArray($style);
            }
            
            // 添加示例数据
            $data = [
                ['SP001', '测试商品1', '食品', '普通商品', '10.00', '9.00', '8.00', '个', '500g', '100', '10', '上架', '示例商品1'],
                ['SP002', '测试服务1', '服务', '服务商品', '100.00', '90.00', '0.00', '次', '', '0', '0', '上架', '示例服务1']
            ];
            
            $row = 2;
            foreach ($data as $item) {
                $col = 'A';
                foreach ($item as $value) {
                    $sheet->setCellValue($col . $row, $value);
                    $col++;
                }
                $row++;
            }

            // 生成文件名
            $filename = '商品导入模板.xlsx';
            $filepath = $exportDir . '/' . $filename;
            
            // 保存文件
            $writer = new Xlsx($spreadsheet);
            $writer->save($filepath);
            
            // 返回文件下载地址
            return json([
                'code' => 0,
                'msg' => '下载成功',
                'data' => [
                    'url' => '/export/' . $filename
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 1,
                'msg' => '下载失败：' . $e->getMessage()
            ]);
        }
    }
} 